<template>
  <js-tree
    :plugins="[
      'search', 'dnd'
    ]"
    :data="this.menuData"
    ref="jsTree"
    @moveNode="setMoveNode"
  >
  </js-tree>
</template>
<script>
import jsTree from '@/components/base/JsTree'
import {httpGetResponse} from '@/service/dataService'
import {arrayToTree, dotData} from '@/assets/scripts/base/functions'
export default {
  name: 'jsTreeMenu',
  components: {
    jsTree
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      menuData: []
    }
  },
  created() {
    this.httpGet()
  },
  mounted() {
    // 绑定click 事件 编辑
    window.$(this.$el).on('click', '.edit', (event) => {
      event.preventDefault()
      const jsTree = window.$(this.$el).jstree(true)
      this.$emit('edit', dotData(jsTree.get_json(event.currentTarget || event.current), 'data.id'))
    })
    // 绑定click 事件 删除
    window.$(this.$el).on('click', '.del', (event) => {
      event.preventDefault()
      const jsTree = window.$(this.$el).jstree(true)
      const node = jsTree.get_json(event.currentTarget || event.current)
      this.$emit('del', node, 'data.id')
    })
    // 绑定click 事件 添加
    window.$(this.$el).on('click', '.create', (event) => {
      event.preventDefault()
      const jsTree = window.$(this.$el).jstree(true)
      this.$emit('create', dotData(jsTree.get_json(event.currentTarget || event.current), 'data.id'))
    })
  },
  destroyed() {
    window.$(this.$el).unbind()
  },
  methods: {
    draw() {
      this.httpGet()
    },
    httpGet() {
      httpGetResponse('/ms-warehouse-order/sorting-maintenance/query-list-warehouse', {werahouseId: this.id}).then(response => {
        console.log(response.data)
        if (Array.isArray(response.data)) {
          this.menuData = []
          this.$emit('setMenuData', response.data)
          let arr = response.data
          let temp = []
          //  <a class="edit" href="javascript: void(0);">编辑</a> <a class="del" href="javascript: void(0);">删除</a>
          arr.forEach(v => {
            temp.push({
              id: v.id,
              text: `<span>` + v.storageRegionName + `</span> <a class="create" href="javascript: void(0);">添加</a>`,
              parentId: v.pId,
              data: v,
              state: {opened: false}
            })
          })
          this.menuData = arrayToTree(temp, 'id', 'parentId', 'children', '0', true)
        }
      })
    },
    setMoveNode(node, event, preJson, nextJson) {
      this.$emit('setMoveNode', node, event, preJson, nextJson)
    },
    search(val) {
      const jsTree = window.$(this.$el).jstree(true)
      jsTree.search(val)
    }
  }
}
</script>
